package com.javen.zookeeper.config;

import com.javen.zookeeper.model.ZookeeperModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.CountDownLatch;

/**
 * @author Javen
 */
@Configuration
@Slf4j
public class ZookeeperConfig {

    @Autowired
    private ZookeeperModel zookeeperModel;

    @Bean(name = "zooKeeper")
    public ZooKeeper zooKeeper() {
        ZooKeeper zooKeeper = null;
        try {
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            zooKeeper = new ZooKeeper(zookeeperModel.getConnectString(),
                    zookeeperModel.getSessionTimeout(),
                    event -> {
                        if (Watcher.Event.KeeperState.SyncConnected == event.getState()) {
                            countDownLatch.countDown();
                        }
                    });
            countDownLatch.await();
        } catch (Exception e) {
            log.error("初始化 Zookeeper 连接异常....", e);
        }
        return zooKeeper;
    }
}
